package com.jh3502.helper.function.person.personlist;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;

import com.jh3502.helper.R;
import com.jh3502.helper.base.BaseActivity;
import com.jh3502.helper.function.person.personnew.PersonNewActivity;
import com.jh3502.helper.utils.Constant;
import com.jh3502.helper.utils.SpHelper;
import com.jh3502.helper.utils.Utils;
import com.jh3502.helper.view.ActionSheetDialog;
import com.jh3502.helper.view.MyRecyclerView;
import com.jh3502.helper.view.SideLetter;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;

/**
 * @author harisucici
 */
public class PersonListCheckActivity extends BaseActivity implements PersonListPresenter.PersonListView {

    @Nullable
    @BindView(R.id.toolbar_title)
    TextView toolbarTitle;
    @Nullable
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @Nullable
    @BindView(R.id.person_list_check_recycler)
    MyRecyclerView personListCheckRecycler;
    @Nullable
    @BindView(R.id.person_list_check_bar)
    SideLetter personListCheckBar;
    @Nullable
    @BindView(R.id.person_list_check_batno)
    TextView personListCheckBatno;
    @Nullable
    @BindView(R.id.person_list_check_bat_name)
    TextView personListCheckBatName;
    @Nullable
    @BindView(R.id.person_list_check_bat_area)
    TextView personListCheckBatArea;
    @Nullable
    @BindView(R.id.person_list_check_size_name)
    TextView personListCheckSizeName;
    private PersonListCheckAdapter mAdapter;
    @NonNull
    private List<PersonListBean> msg = new ArrayList<>();
    private String batchNo;
    private String batchTitle;
    @NonNull
    private String[] selectOnline = {"全部", "已修订", "未修订"};
    private String maleID, femaleID;
    private PersonListPresenter personListPresenter;
    private List<PersonListBean> personListAll;
    private int showIndex = 0;//设置筛选依据
    private int all;//人员总数
    private int checked;//已经选择

    @Override
    protected int setViewId() {
        return R.layout.activity_person_list_check;
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_up, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                onBackPressed();
                break;
            case R.id.action_update:
                if (all != checked) {
                    showShortToast("未审核完,不允许上传");

                } else {
                    Map<String, Object> body = new HashMap<>(2);
                    body.put("batno", batchNo);
                    body.put("title", batchTitle);
                    body.put("maleID", maleID);
                    body.put("femaleID", femaleID);
                    body.put("ltBatPersonDOLst", SpHelper.getInstance().getPersonList(batchNo));
                    personListPresenter.toSaveoneall(body);
                }

                break;
            case R.id.action_filter:
                ActionSheetDialog actionSheetDialogType = new ActionSheetDialog(this);
                actionSheetDialogType.builder().setCancelable(false).setCanceledOnTouchOutside(true);

                for (int i = 0; i < selectOnline.length; i++) {
                    String title = selectOnline[i];
                    int finalI = i;
                    actionSheetDialogType.addSheetItem(title, R.color.green, () -> {
                        showCheck(finalI);
                    });
                }
                actionSheetDialogType.show();
                break;
            default:
                break;
        }
        return true;
    }

    @Override
    protected void initView() {
        toolbar.setTitle("");
        toolbarTitle.setText("人员列表");
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        personListPresenter = new PersonListPresenter();
        personListPresenter.setPersonListView(this);
        Map<String, Object> batInfo = Utils.getInstance().jso2map(SpHelper.getInstance().getBatAct());
        batchNo = (String) batInfo.get("batno");
        batchTitle = (String) batInfo.get("title");
        personListAll = SpHelper.getInstance().getPersonList(batchNo);
        personListCheckBatno.setText(batchNo);
        batchTitle = (String) batInfo.get("title");
        personListCheckBatName.setText(batchTitle);
        personListCheckBatArea.setText((String) batInfo.get("region"));
        maleID = (String) batInfo.get("maleID");
        femaleID = (String) batInfo.get("femaleID");
        ArrayList<Map<String, Object>> ruleList = Utils.getInstance().jsa2list(SpHelper.getInstance().getListltruleMale());
        for (Map<String, Object> map : ruleList) {
            if (maleID.equals(map.get("id"))) {
                personListCheckSizeName.setText((String) map.get("name"));
            }
        }
        // 取得完整列表
        mAdapter = new PersonListCheckAdapter(this, msg);
        personListCheckRecycler.setAdapter(mAdapter);
        mAdapter.setOnItemClickListener(s -> {
            if (Utils.getInstance().isFastDoubleClick()) {
                return;
            }
            PersonListBean personListBean = msg.get(Integer.parseInt(s));
            Bundle bundle = new Bundle();
            bundle.putInt("type", Constant.PERSON_DETAIL_ACTIVITY);
            bundle.putString("batchNo", batchNo);
            bundle.putString("batchTitle", batchTitle);
            bundle.putString("pno", personListBean.getPno());
            bundle.putString("maleId", maleID);
            bundle.putString("femaleId", femaleID);
            bundle.putString("title", toolbarTitle.getText().toString());
            Utils.getInstance().startActivity(this, PersonNewActivity.class, bundle);
        });
        mAdapter.setOnItemLongClickListener(s -> {
            ActionSheetDialog actionSheetDialogType = new ActionSheetDialog(this);
            actionSheetDialogType.builder().setTitle("是否删除该用户").setCancelable(false).setCanceledOnTouchOutside(true);
            actionSheetDialogType.addSheetItem("确定", R.color.green,
                    () -> {
                        msg.remove(Integer.parseInt(s));
                        SpHelper.getInstance().setPersonListBean(batchNo, msg);
                        mAdapter.notifyDataSetChanged();
                    });
            actionSheetDialogType.show();
        });

        mAdapter.setButtonOnclickCheck(position -> {
            String pno = msg.get(position).getPno();
            boolean isCheck = msg.get(position).isCheck();
            msg.get(position).setCheck(!isCheck);
            mAdapter.notifyDataSetChanged();

            for (int i = 0; i < personListAll.size(); i++) {
                PersonListBean personListBean = personListAll.get(i);
                if (personListBean.getPno().equals(pno)) {
//                    personListAll.remove(i);//移除原来的
                    personListBean.setCheck(!isCheck);
//                    personListAll.add(personListBean);
//                    SpHelper.getInstance().setPersonList(batchNo, personListAll);//放回去
                }
            }

            // 统计量体人数
            checked = 0;
            for (PersonListBean personListBean : personListAll) {
                if (personListBean.getLtDataDO() != null) {
                    if (personListBean.isCheck()) {
                        checked++;
                    }
                }
            }
            toolbarTitle.setText("全部" + all + "人 已修订" + checked + "人 未修订" + (all - checked) + "人");
        });
        personListCheckBar.setOnTouchLetterChangedListener(letter -> {
            // 从集合中查找第一个拼音首字母为letter的索引, 进行跳转
            for (int i = 0; i < msg.size(); i++) {
                PersonListBean personListBean = msg.get(i);
                String s = personListBean.getNamePinyin().charAt(0) + "";
                if (TextUtils.equals(s, letter)) {
                    // 匹配成功, 中断循环, 跳转到i位置
                    personListCheckRecycler.MoveToPosition(i);
                    break;
                }
            }
        });


    }

    @Override
    protected void initData() {
    }

    @Override
    protected void doOnDestroy() {

    }

    @Override
    protected void doOnResume() {
        showCheck(showIndex);

        // 统计量体人数
        checked = 0;
        for (PersonListBean personListBean : personListAll) {
            if (personListBean.getLtDataDO() != null) {
                if (personListBean.isCheck()) {
                    checked++;
                }
            }
        }
        toolbarTitle.setText("全部" + all + "人 已修订" + checked + "人 未修订" + (all - checked) + "人");
    }

    @Override
    protected void doOnSaveInstanceState(Bundle savedInstanceState) {
    }

    @Override
    public void responseError(int code, String msg) {

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            String path;
            switch (requestCode) {
                case Constant.CONNECT_BLUE_TOOTH:
                    initBlueTooth();
                    break;
                default:
                    break;
            }
        }
    }

    @Override
    public void saveoneallSuccess() {
        showShortToast("上传成功");
    }

    private void showCheck(int i) {

        showIndex = i;

        all = personListAll.size();
        ArrayList<PersonListBean> personList = new ArrayList<>(2);
        switch (i) {
            case 0:
                msg.clear();
                msg.addAll(personListAll);
                Collections.sort(msg);
                mAdapter.notifyDataSetChanged();
                break;
            case 1:
                msg.clear();
                for (PersonListBean personListBean : personListAll) {
                    if (personListBean.isCheck()) {
                        personList.add(personListBean);
                    }
                }
                msg.addAll(personList);
                Collections.sort(msg);
                mAdapter.notifyDataSetChanged();
                break;
            case 2:
                msg.clear();
                for (PersonListBean personListBean : personListAll) {
                    if (!personListBean.isCheck()) {
                        personList.add(personListBean);
                    }
                }
                msg.addAll(personList);
                Collections.sort(msg);
                mAdapter.notifyDataSetChanged();
                break;
            default:
                break;
        }

    }


}
